package com.captain.leetcode2.链表;

import com.captain.leetcode.链表.ListNode;

/**
 * Des:
 * <p>
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 * 输入：l1 = [1,2,4], l2 = [1,3,4]
 * 输出：[1,1,2,3,4,4]
 * <p>
 * 输入：l1 = [], l2 = []
 * 输出：[]
 * <p>
 * 输入：l1 = [], l2 = [0]
 * 输出：[0]
 *
 * @author XL
 * @Date 2021/8/30 17:17
 */
public class 合并两个有序链表21 {

    public static void main(String[] args) {
        ListNode listNode = new 合并两个有序链表21().mergeTwoLists(ListNode.getInstance(), ListNode.getInstance());
        System.out.println(listNode);
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode pre = new ListNode(-1);
        ListNode dummy = pre;
        while (l1 != null && l2 != null) {
            int val1 = l1.val;
            int val2 = l2.val;
            //如果l1 大
            if (val1 <= val2) {
                dummy.next = new ListNode(val1);
                l1 = l1.next;
                dummy = dummy.next;
                continue;
            }
            if (val2 <= val1) {
                dummy.next = new ListNode(val2);
                l2 = l2.next;
                dummy = dummy.next;
            }
        }
        //出来之后, 如果还有值
        if (l1 != null) dummy.next = l1;
        if (l2 != null) dummy.next = l2;
        return pre.next;
    }
}
